import { http } from '@/utils/http';

/** 文件上传通用返回类型 */
export type UploadResult = {
  url: string;
  filename: string;
  size: number;
  mimetype: string;
};

/** 基础上传响应类型 */
export type UploadResponse = {
  code: number;
  msg: string;
  data: UploadResult | UploadResult[];
};

/**
 * 通用文件上传
 * @param data - 表单数据
 * @returns 上传结果
 */
export const commonUploadApi = (data: FormData) => {
  return http.request<UploadResponse>(
    'post',
    '/upload/commonUpload',
    {
      data,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
};

/**
 * Base64格式文件上传
 * @param data - 包含base64数据的对象
 * @returns 上传结果
 */
export const commonBase64UploadApi = (data: {
  filename: string;
  base64: string;
  mimetype?: string;
}) => {
  return http.request<UploadResponse>(
    'post',
    '/upload/commonUploadBase64',
    { data }
  );
};

/**
 * 单张图片上传
 * @param file - 图片文件
 * @returns 上传结果
 */
export const uploadSingleImageApi = (file: File) => {
  console.log(file)
  const formData = new FormData();
  formData.append('file', file);

  return http.request<UploadResponse>(
    'post',
    '/upload/singleImg',
    {
      data: formData,
      // 添加正确的Content-Type配置，让浏览器自动处理boundary
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
};

/**
 * 多张图片上传
 * @param files - 图片文件数组
 * @returns 上传结果
 */
export const uploadMultipleImageApi = (files: File[]) => {
  const formData = new FormData();
  files.forEach(file => {
    formData.append('files', file);
  });

  return http.request<UploadResponse>(
    'post',
    '/upload/multipleImg',
    {
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
};

/**
 * 单个文件上传
 * @param file - 任意类型文件
 * @returns 上传结果
 */
export const uploadSingleFileApi = (file: File) => {
  const formData = new FormData();
  formData.append('file', file);

  return http.request<UploadResponse>(
    'post',
    '/upload/singleFile',
    {
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
};

/**
 * 多个文件上传
 * @param files - 任意类型文件数组
 * @returns 上传结果
 */
export const uploadMultipleFileApi = (files: File[]) => {
  const formData = new FormData();
  files.forEach(file => {
    formData.append('files', file);
  });

  return http.request<UploadResponse>(
    'post',
    '/upload/multipleFile',
    {
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
};
